package com.dongdongshop.controller;

import com.alibaba.fastjson.JSONObject;
import com.dongdongshop.constant.HttpResultEnum;
import com.dongdongshop.data.DataResult;
import com.dongdongshop.pojo.user.TbUser;
import com.dongdongshop.service.user.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Author Eayon
 * @Date 2020/4/3 16:04
 */
@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 根据用户名称查询
     * @param username
     * @return
     */
    @GetMapping("/getByUsername/{username}")
    public DataResult getByUsername(@PathVariable("username")String username){
        List<TbUser> users = null;
        try {
            users = userService.getByUsername(username);
        }catch (Exception e){
            return new DataResult(HttpResultEnum.ERROR.getCode(),HttpResultEnum.ERROR.getMessage());
        }
        return new DataResult(HttpResultEnum.SUCCESS.getCode(),HttpResultEnum.SUCCESS.getMessage(),users);
    }

    @PostMapping("/addUser")
    public DataResult addUser(String user){
        try {
            TbUser tbUser = JSONObject.parseObject(user, TbUser.class);
            userService.addUser(tbUser);
        }catch (Exception e){
            return new DataResult(HttpResultEnum.ERROR.getCode(),HttpResultEnum.ERROR.getMessage());
        }
        return new DataResult(HttpResultEnum.SUCCESS.getCode(),HttpResultEnum.SUCCESS.getMessage());
    }
}
